<template>

  <div style="margin-top: 22px">

      <el-radio-group v-model="radio1" style="background-color: aqua;">

          <el-radio-button label="全部题目" @click="handleRadioChange('0')"></el-radio-button>

          <el-radio-button label="已删除" @click="handleRadioChange('1')"></el-radio-button>
      </el-radio-group>

      <el-row>

          <el-col :span="24" style="margin-top: 22px">

              <el-form :inline="true" :model="formData">

                  <el-form-item label="题目内容：">

                      <el-input v-model="formData.questionTitle" />

                  </el-form-item>

                  <el-form-item label="所属测评：">

                      <el-input v-model="formData.testId" />

                  </el-form-item>

                  <el-form-item>

                      <el-button type="primary" @click="getAllQuestions">

                          搜索

                      </el-button>
                      <el-button @click="addQuestion" type="primary">

                          新增题目

                      </el-button>
                      <el-button type="danger" @click="removBatch">

                          批量删除

                      </el-button>

                  </el-form-item>

              </el-form>

          </el-col>

      </el-row>

      <el-row style="margin-bottom: 10px;">

          <el-col :span="24">
              <!-- 绑定传递数据的空表单 -->
              <el-table :data="tableData" border :header-cell-style="{ background: '#87cefa', color: '#FFF' }" stripe
                  style="width: 100%" @selection-change="handleSelectionChange">
                  <!-- 复选框 -->
                  <!-- <el-table-column type="selection" width="55"></el-table-column> -->
                  <el-table-column type="selection" :selectable="selectable" width="55" />
                  <!-- prop对应传递数据的变量名属性，lablel对应显示名称 -->
                  <el-table-column prop="id" label="题目选项ID" align="center" />
                  <el-table-column prop="optionContent" label="选项内容" align="center" />
                  <!-- <el-table-column prop="questionOption.optionContent" label="选项内容" align="center" />
                  <el-table-column prop="questionOption.score" label="分值" align="center" /> -->
                  <el-table-column prop="questionTitle" label="题目内容" align="center">
                </el-table-column>
                <el-table-column prop="psychologicalTest.testName" label="所属测评" align="center" clear>
                  <!-- <template #default="scope">
                    <span>{{ scope.row.psychologicalTest ? scope.row.psychologicalTest.testName : '无测评' }}</span>
                  </template> -->
                </el-table-column>                 
                  <el-table-column prop="score" label="分值" align="center" >
                </el-table-column>

                  <el-table-column label="操作" align="center">
                      <!-- 插槽中绑定默认插槽，允许你访问当前行的数据 -->
                      <template #default="scope">
                          <!-- scope对象包含了当前行的数据，其中scope.row就是当前行的数据对象 -->
                          <el-button size="small" type="primary" @click="editQuestion(scope.row)"
                              :underline="false">修改题目</el-button>
                          <el-button  v-if="scope.row.del=='0'" size="small" type="danger" @click="deleteQuestion(scope.row.id)"
                              :underline="false">删除题目</el-button>
                          <el-button v-else size="small" type="primary" :underline="false"
                              @click="enableQuestion(scope.row )">启用</el-button>
                      </template>

                  </el-table-column>

              </el-table>

          </el-col>

      </el-row>
      <!-- 弹出弹窗，填写测评信息 -->
      <el-dialog v-model="dialogVisible" :title="title" width="500">

          <el-form :model="testData">
              <el-form-item label="选项内容" label-width="80px">
                  <el-input v-model="testData.optionContent" autocomplete="off" placeholder="请输入题目名称"></el-input>
              </el-form-item>
              <el-form-item label="题目内容" label-width="80px">
                  <el-input v-model="testData.questionTitle" autocomplete="off" placeholder="请输入选项内容"></el-input>
              </el-form-item>
              <!-- <el-form-item label="所属测评" label-width="80px">
                  <el-input v-model="testData.psychologicalTest.testName" autocomplete="off" placeholder="请输入题目所属测评"></el-input>
              </el-form-item> -->

              <el-form-item label="所属测评" label-width="80px">
                  <el-select v-model="psychologicalTest.testName" placeholder="请选择测评">
                    <el-option v-for="item in psychologicalTest" :key="item.id" :label="item.label" :value="item.testName"/>
                  </el-select>
              </el-form-item>

              <el-form-item label="分值" label-width="80px">
                  <el-input v-model="testData.score" autocomplete="off" placeholder="请输入选项分值"></el-input>
              </el-form-item>
          </el-form>
          <template #footer>
              <div class="dialog-footer">
                  <el-button @click="cancle">取 消</el-button>
                  <el-button type="primary" @click="confirm">确 定</el-button>
              </div>
          </template>
      </el-dialog>
      <!-- 页码 -->
      <el-row>
          <!-- 定义了一个分页组件 -->
          <!-- 将formData.pageSize的值绑定到了MyComponent组件的page-size属性上 -->
          <!-- 当current-change事件被触发时，Vue会调用组件实例上的pageNumChange方法 -->
          <el-pagination size="small" layout="prev, pager, next" :total="total" :page-size="formData.pageSize"
              @current-change="pageNumChange" />
      </el-row>
  </div>
</template>

<script setup>
import { onMounted, ref,getCurrentInstance } from 'vue';
const dialogVisible = ref(false)
import { ElMessage } from 'element-plus';
//响应式数组，用于存储从服务器获取的数据，这些数据会在表格中展示给题目
const tableData = ref([]);
//接收全局对象
const CurrentInstance=getCurrentInstance()
//获取全局对象挂载的naxios赋值给$http来代替naxios
const {$http}=CurrentInstance.appContext.config.globalProperties
// 响应式对象，接收要查找的必要数据
import { ElMessageBox } from 'element-plus';


const formData = ref({
  pageNum: 1,
  pageSize: 10,
  //查题目
  questionTitle:"",
  //查所属测评
  testId: "",
  ids:[],
  del:"0",
});
//响应式对象，用于存储和管理与单个题目相关的各种参数和数据
let testData = ref({
  addOrUpdateFlag: 1,
  // 题目选项id
  id: '',
  optionContent: '',
  questionTitle: '',
  score: '',
  testId: '',
  del: 0,
  // 题目所属测评
  psychologicalTest: {},
});

const total = ref(0);

let title = ref('')

// 存放测评类型
const psychologicalTest = ref([])

//批量删除
const selectable = (row) => ![].includes(row.id)
const handleSelectionChange = (val) => {
formData.value.ids = val.map(item => item.id);
}
// 在组件挂载完成后调用 getAllQuestions 方法来获取测试数据列表
onMounted(() => {
  getAllQuestions();
});

// function handleSelectionChange(val) {
//         this.ids = val.map(item => item.id);
//     }
function addQuestion() {
  //修改标题为新增题目
  title.value = '新增题目'
  //显示对话框
  dialogVisible.value = true
  //状态为1时代表添加数据
  testData.value.addOrUpdateFlag = 1
}
// 从后台请求数据列表
function getAllQuestions() {
  $http({
      method: 'get',
      url: 'http://localhost:8081/sfzy/questionOption/page', // 根据你的API路径调整
      params: formData.value
  }).then((res) => {
      if (res.data.code === 200) {
          // 更新为正确的数据路径
          tableData.value = res.data.data.list; 
          // 更新为正确的总记录数路径
          total.value = res.data.data.total; 
      } else {
          ElMessage.error('获取题目列表失败');
      }
  }).catch((error) => {
      ElMessage.error('获取题目列表失败');
  });

  // 获取测评类型
  $http({
        method: 'get',
        url: 'http://localhost:8081/sfzy/psychologicalTest/page', // 根据你的API路径调整
        // params: formData.value
    }).then((res) => {
        console.log(res,'=================================');
        psychologicalTest.value = res.data.data.list;
    });
}

//确定添加
function confirm() {
  const method = testData.value.addOrUpdateFlag == 2 ? 'put' : 'post';
  // console.log(testData.value,'=================================');
  const url = 'http://localhost:8081/sfzy/questionOption';
  $http({
      method: method,
      url: url,
      data: testData.value
  }).then((res) => {
      if (res.data.code == 200) {
          ElMessage.success(method === 'post' ? "添加成功" : "修改成功");
          testData.value = {}
      } else {
          ElMessage.error('操作失败!');
      }
      dialogVisible.value = false;
      getAllQuestions();
  }).catch((error) => {
      ElMessage.error('请求失败!');
      console.error('请求失败:', error);
  });
}

//取消添加
function cancle() {
  dialogVisible.value = false;
  testData.value = {}
}
function editQuestion(row) {
  testData.value = row
  title.value = '修改测评'//修改标题
  dialogVisible.value = true//显示对话框
  testData.value.addOrUpdateFlag = 2
}


function deleteQuestion(id) {
  ElMessageBox.confirm('是否确认删除选中的数据?', '删除', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
  }).then(() => {
      console.log('===========deleteQuestion============',id);
      $http({
      method: 'delete',
      url: 'http://localhost:8081/sfzy/questionOption/' + id,
  }).then(res => {
          if (res.status === 200) {
              ElMessage.success('删除成功')
              getAllQuestions();
          } else {
              ElMessage.error('删除失败')
          }
      })
  }).catch(() => {
      ElMessage({
          type: 'info',
          message: "取消删除操作"
      })
  });
}

// 批量删  
function removBatch(){
  
      ElMessageBox.confirm('是否确认删除选中的数据?', '删除', 
          {
          confirmButtonText: '确认', // 确认按钮
          cancelButtonText: '取消', // 取消按钮
          type: 'warning',// 警告的图标
          }
      )
      .then(() => {
        const idsArray = formData.value.ids;
        const idsStr = idsArray.join(",");
        
         // 点击确认 删除操作
         $http({
              method:'delete',
              url:`http://localhost:8081/sfzy/questionOption?ids=${idsStr}`,
              data:{}
          }).then(res=>{
              if(res.status== 200){
                  ElMessage.success('删除成功')
                  // 判断当前页是否还有数据，如果没有则将页码减1
                  if (tableData.value.length === 0 && formData.value.pageNum > 1) {
                   formData.value.pageNum--;
              }
              // 清理ids参数
              formData.value.ids = [];
                  getAllQuestions();
              }else{
                  ElMessage.error('删除失败')
              }
          })
      }).catch(() => {
          ElMessage({
              type: 'info',
              message: "取消删除操作",
          })
      })
  }
function pageNumChange(num) {
  // 更新表单数据中的页码
  formData.value.pageNum = num;
  // 调用获取所有测试的方法
  getAllQuestions();

}

function handleRadioChange(status) {
  // 更新表单数据中的status值
  formData.value.del = status;
  // 获取所有测试数据
  getAllQuestions();

}

// 恢复测评
function enableQuestion(row) {
  updateStatus(row.id, '0');
}
function updateStatus(id, del) {
  axios({
      method: 'put',
      url: `http://localhost:8081/sfzy/questionOption`,
      data: {
          id: id,
          del: del
      }
  }).then((res) => {
      console.log('Response:', res.data);
      if (res.data.status == 200) {
          ElMessage.success("修改成功");
      } else {
          ElMessage.error('修改失败');
      }
      getAllQuestions();
  }).catch((error) => {
      console.error('Error:', error);
      ElMessage.error('修改测评状态失败');
  });
}
</script>

<style scoped></style>